/**
 * related to toOrder.ui
 * 
 * @Author : chenglm
 * @Timestamp : 2016-07-06
 */
var app = sm("do_App");
var page = sm("do_Page");
var rootview = ui("$");
var nf = sm("do_Notification");
var hashdata = mm("do_HashData");
var homemakingUtil = require("url/homemaking");
var qqHttp = require("helper/http");
var orderHelper = require("helper/order");
var userUrl = require("url/user");
var couponUrl = require("url/coupon");
var httpSilence = require("helper/httpSilence");
var do_LinearLayout_item = ui("do_LinearLayout_item");
var do_Button_order = ui("do_Button_order");
var do_ALayout_address = ui("do_ALayout_address");
var do_Label_address = ui("do_Label_address");
var label_canServiceCount = ui("label_canServiceCount");
var aLayout_member = ui("aLayout_member");
var linearLayout_showMember = ui("linearLayout_showMember");
var aLayout_showMember = ui("aLayout_showMember");
var label_showMember = ui("label_showMember");
var imageView_memberImg = ui("imageView_memberImg");
var textField_remark = ui("textField_remark");
var label_remark = ui("label_remark");
var label_remind = ui("label_remind");
var helperOpen = require("helper/open");
var do_ALayout_coupon=ui("do_ALayout_coupon");

var param = {};
var paramCheck = {};
var addItems = [];
var flag = false;

var type;
var pubitemVoList;
var minuteIntervals = 0;

//andriod返回键
page.on("back", function() {
    app.closePage();
});

page.on("result", function(data) {
	if (data) {
		if (data.nextAddr || data.houseNumber) {
			do_Label_address.text = data.contactName + " " + data.address;
			param.addressId = data.id;
			selectId= data.id;
			param.x = data.x;
			param.y = data.y;
			paramCheck.x = data.x;
			paramCheck.y = data.y;
			paramCheck.communityId = data.communityId;
			getServiceMember();
		} else if (data.fromPage && data.fromPage=='memberList') {
			aLayout_member.visible = false;
			linearLayout_showMember.visible = true;
			imageView_memberImg.source = data.fileDomain+data.photosImg;
			label_showMember.text = data.realName + " 籍贯：" + data.birthPlace;
			label_showMember.tag = data.id;
			label_remark.text = data.remark;
		}
	}
});

/* 头部 */
var headerAout = ui("do_ALayout_header");
var addheader = headerAout.add("header", "source://view/reuse/header.ui", 0, 0);
var header = ui("header");
//左上角-返回
var headerLeft = ui(addheader+".headerLeft");
var labelTitle = ui(addheader+".labelTitle");
headerLeft.on("touch", function() {
    app.closePage();
});
//右上角
var headerRight = ui(addheader+".headerRight");
var labelNext = ui(addheader+".labelNext");
labelNext.visible = true;
labelNext.text = "服务说明";
headerRight.on("touch", function() {
	helperOpen.open("source://view/homemaking/detail/detail.ui",{id:type.id});
});
page.on("loaded", function(){
	//读取当前页面的传入参数
	var data = page.getData();
	init(data);
});
page.on("refreshTime",function(data){
	//deviceone.print(JSON.stringify(data));
	var showTime = ui("do_Label_showTime");
	showTime.text = data.serviceDateStr + " " + data.serviceHourStr;
	param.serviceDateStr = data.serviceDateStr;
	param.serviceHourStr = data.serviceHourStr;
	paramCheck.serviceDateStr = data.serviceDateStr;
	paramCheck.serviceHourStr = data.serviceHourStr;
	getServiceMember();
});
page.on("refreshSelectMemberType",function(data){
	if (data.type == 1) { //自己选服务人员
		var homemakingPubitemVos = [];
		for (var i=0; i<addItems.length; i++) {
			var addItem = addItems[i];
			var pubitemName = ui(addItem.addItemUi+".do_Label_itemName").text.trim();
			var count = Number(ui(addItem.addItemUi+".do_Label_num").text.trim());
			if (count > 0) {
				var homemakingPubitemVoTem = {"id":""};
				homemakingPubitemVoTem.id = addItem.itemId;
				homemakingPubitemVoTem.quantity = count;
				homemakingPubitemVoTem.name = pubitemName;
				homemakingPubitemVos.push(homemakingPubitemVoTem);
			}
		}
		paramCheck.homemakingPubitemVos = homemakingPubitemVos;
		helperOpen.open("source://view/homemaking/detail/memberList.ui",paramCheck);
	} else { //系统帮选
		var homemakingPubitemVos = [];
		for (var i=0; i<addItems.length; i++) {
			var addItem = addItems[i];
			var pubitemName = ui(addItem.addItemUi+".do_Label_itemName").text.trim();
			var count = Number(ui(addItem.addItemUi+".do_Label_num").text.trim());
			if (count > 0) {
				var homemakingPubitemVoTem = {"id":""};
				homemakingPubitemVoTem.id = addItem.itemId;
				homemakingPubitemVoTem.quantity = count;
				homemakingPubitemVoTem.name = pubitemName;
				homemakingPubitemVos.push(homemakingPubitemVoTem);
			}
		}
		paramCheck.homemakingPubitemVos = homemakingPubitemVos;
		if (paramCheck.homemakingPubitemVos && paramCheck.homemakingPubitemVos.length > 0) {
			paramCheck.typeId = type.id;
			qqHttp.post(homemakingUtil.url.base.getCanServiceMemberOne, paramCheck, function(data) {
				if (data.member) {
					aLayout_member.visible = false;
					linearLayout_showMember.visible = true;
					imageView_memberImg.source = data.member.fileDomain+data.member.photosImg;
					label_showMember.text = data.member.realName + " 籍贯：" + data.member.birthPlace;
					label_showMember.tag = data.member.id;
					label_remark.text = data.member.remark;
				}
			});
		}
	}
});
page.on("getServiceMemberCount", function(data){
	getServiceMember();
});
function init(data) {
	qqHttp.post(homemakingUtil.url.type.detailType, {id:data.typeId}, function(data) {
		//deviceone.print(JSON.stringify(data));
		//默认地址
		if (data.userAddress) {
			var userAddress = data.userAddress;
			do_Label_address.text = userAddress.contactName + " " + userAddress.address;
			param.addressId = userAddress.id;
			selectId= userAddress.id;
			param.x = userAddress.x;
			param.y = userAddress.y;
			paramCheck.x = userAddress.x;
			paramCheck.y = userAddress.y;
			paramCheck.communityId = userAddress.communityId;
		}
		type = data.type;
		pubitemVoList = data.pubitemVoList;
		labelTitle.text = type.name;
		for(var i=pubitemVoList.length-1;i >= 0;i--) {
			var addItem = do_LinearLayout_item.add("item"+i, "source://view/homemaking/detail/toOrderItem.ui", 0, 0);
			var do_Label_itemName = ui(addItem+".do_Label_itemName");
			var do_TextField_count = ui(addItem+".do_Label_num");
			do_Label_itemName.text = pubitemVoList[i].name;
			addItems.push({itemId:pubitemVoList[i].id,addItemUi:addItem});
		}
		if (type.id == homemakingUtil.typeId.DailyCleaning) {
			label_remind.text = label_remind.text + "\r\n参考：一居室1小时，二居室2小时，三居室3小时";
			page.fire("setMaxMin",{max:4,min:1});
			minuteIntervals = 0.30;
		} else {
			label_remind.text = label_remind.text;
			page.fire("setMaxMin",{max:99,min:0});
		}
		myCouponList();
	});
}

var selectId;
do_ALayout_address.on("touch", function() {
	helperOpen.open("source://view/user/userAddress/list.ui",{select:true,selectId:selectId});
});

var layout_selectTime = ui("layout_selectTime");
var selectTimeUi = ui(rootview.add("selectTime","source://view/homemaking/detail/selectTime.ui",0,0));
layout_selectTime.on("touch","",300,function(){
	page.hideKeyboard();
	page.fire("times");
	page.fire("getTimes",{typeId:type.id,flag:1,hourIntervals:1,minuteIntervals:minuteIntervals});
});

//服务人员列表
//var selectMemberTypeUi = ui(rootview.add("selectMemberType","source://view/homemaking/detail/selectMemberType.ui",0,0));
aLayout_member.on("touch", function() {
	page.hideKeyboard();
	if (Number(label_canServiceCount.text) > 0) {
		//page.fire("showMemberType");
		
		var homemakingPubitemVos = [];
		for (var i=0; i<addItems.length; i++) {
			var addItem = addItems[i];
			var pubitemName = ui(addItem.addItemUi+".do_Label_itemName").text.trim();
			var count = Number(ui(addItem.addItemUi+".do_Label_num").text.trim());
			if (count > 0) {
				var homemakingPubitemVoTem = {"id":""};
				homemakingPubitemVoTem.id = addItem.itemId;
				homemakingPubitemVoTem.quantity = count;
				homemakingPubitemVoTem.name = pubitemName;
				homemakingPubitemVos.push(homemakingPubitemVoTem);
			}
		}
		paramCheck.homemakingPubitemVos = homemakingPubitemVos;
		helperOpen.open("source://view/homemaking/detail/memberList.ui",paramCheck);
	}
});
aLayout_showMember.on("touch", function() {
	helperOpen.open("source://view/homemaking/detail/memberList.ui",paramCheck);
	//page.fire("showMemberType");
});

do_Button_order.on("touch", function(data, e){
	if (flag && Number(label_canServiceCount.text) == 0) {
		nf.toast("该时间没有可预约的人员，请选择其他时间");
		return;
	}
	nf.confirm({text:"亲爱的用户，为保障保洁师的时间效益，如果在服务开始前2个小时内取消订单，将扣除您订单金额的一定比例数，使用的代金券将优先抵扣。恳请您谅解。\n前2小时外取消，退还100%;\n2小时内取消，退还50%",title:"温馨提示",button1text:"同意",button2text:"取消"},function(datacall,e){
		if(datacall == 1){
			var homemakingOrderItemVos = [];
			for (var i=0; i<addItems.length; i++) {
				var addItem = addItems[i];
				var count = Number(ui(addItem.addItemUi+".do_Label_num").text.trim());
				var pubitemName = ui(addItem.addItemUi+".do_Label_itemName").text.trim();
				if (count > 0) {
					var homemakingOrderItemVo = {"homemakingPubitemId":addItem.itemId,"count":count,"pubitemName":pubitemName};
					homemakingOrderItemVos.push(homemakingOrderItemVo);
				}
			}
			param.homemakingOrderItemVos = homemakingOrderItemVos;
			param.baseId = label_showMember.tag;
			param.buyerRemark = textField_remark.text;
			if(null!=couponVo){
				param.couponUserId=couponVo.id;
				param.minusPrice=couponVo.minusPrice;
			}
			qqHttp.post(homemakingUtil.url.order.add, param, function(data) {
				nf.toast("下单成功");
				if (data.payStatus == 2 || data.payType == 1) { //免费的或者货到付款的
					helperOpen.open("source://view/order/detail.ui", {orderNo : data.orderNo});
				} else {
					orderHelper.toPay(data.orderNo);
				}
			});
		}
	});
});
//优惠卷列表
var addCoupon = rootview.add("coupon",
		"source://view/reuse/form/oneCategory.ui", 0, 0);
var couponList=[];
do_ALayout_coupon.on("touch", "", 300, function() {
	var ptitle = {
			"title" : "选择优惠劵",
			"id" : "coupon"
		}
	var pcount = [ptitle, couponList];
	page.fire("oneCategoryList", pcount);
	page.fire("oneCategory", "true");
});
var couponVo=null;
page.on("refreshOneCategory", function(data) {
	if ("coupon" == data[1]) {
		ui("do_Label_16").text = data[0].onename;
		for (var i = 0; i < couponList.length; i++) {
			if(data[0].oneid==couponList[i].id){
				couponVo=couponList[i];
				break;
			}
		}
	}
});
function myCouponList(){
	var params = {
		homeMakingTypeId:page.getData().typeId
	};
	httpSilence.post(couponUrl.url.user.homemakingCoupon, params, function(data) {
		if(data.list.length>0){
			do_ALayout_coupon.visible=true;
			for (var i = 0; i < data.list.length; i++) {
				if(null!=data.list[i].strExpireAt&&''!=data.list[i].strExpireAt){
					data.list[i].name=data.list[i].name+"  有效期:"+data.list[i].strExpireAt;
				}else{
					data.list[i].name=data.list[i].name;
				}
			}
			couponList=data.list;
		}else{
			do_ALayout_coupon.visible=false;
		}
	});
}
function getServiceMember() {
	if (paramCheck.serviceDateStr && paramCheck.serviceHourStr && paramCheck.x && paramCheck.y) {
		//重置
		aLayout_member.visible = true;
		linearLayout_showMember.visible = false;
		label_showMember.text = "";
		label_showMember.tag = "";
		label_remark.text = "";
		
		var homemakingPubitemVos = [];
		for (var i=0; i<addItems.length; i++) {
			var addItem = addItems[i];
			var pubitemName = ui(addItem.addItemUi+".do_Label_itemName").text.trim();
			var count = Number(ui(addItem.addItemUi+".do_Label_num").text.trim());
			if (count > 0) {
				var homemakingPubitemVoTem = {"id":""};
				homemakingPubitemVoTem.id = addItem.itemId;
				homemakingPubitemVoTem.quantity = count;
				homemakingPubitemVoTem.name = pubitemName;
				homemakingPubitemVos.push(homemakingPubitemVoTem);
			}
		}
		paramCheck.homemakingPubitemVos = homemakingPubitemVos;
		if (paramCheck.homemakingPubitemVos && paramCheck.homemakingPubitemVos.length > 0) {
			paramCheck.typeId = type.id;
			qqHttp.post(homemakingUtil.url.base.getCanServiceMemberCount, paramCheck, function(data) {
				label_canServiceCount.text = data.count;
				flag = true;
			});
		}
	}
}

function fD(a, b, c) {
	for (; a > c;)
		a -= c - b;
	for (; a < b;)
		a += c - b;
	return a;
};
function jD(a, b, c) {
	b != null && (a = Math.max(a, b));
	c != null && (a = Math.min(a, c));
	return a;
};
function yk(a) {
	return Math.PI * a / 180
};
function Ce(a, b, c, d) {
	var dO = 6370996.81;
	return dO * Math.acos(Math.sin(c) * Math.sin(d) + Math.cos(c) * Math.cos(d) * Math.cos(b - a));
};
function getDistance(a, b) {
	if (!a || !b)
		return 0;
	a.lng = fD(a.lng, -180, 180);
	a.lat = jD(a.lat, -74, 74);
	b.lng = fD(b.lng, -180, 180);
	b.lat = jD(b.lat, -74, 74);
	return Ce(yk(a.lng), yk(b.lng), yk(a.lat), yk(b.lat));
};